# app/crud.py
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from app.models import schemas, models
from app.core import security
import logging

logger = logging.getLogger(__name__)


async def get_user_by_username(db: AsyncSession, username: str):
    """根据用户名获取用户 - 异步版本"""
    try:
        result = await db.execute(select(models.User).filter(models.User.username == username))
        return result.scalars().first()
    except Exception as e:
        logger.error(f"获取用户失败: {str(e)}")
        return None


async def create_user(db: AsyncSession, user: schemas.UserCreate):
    """创建新用户 - 异步版本"""
    try:
        # 哈希密码
        hashed_password = security.get_password_hash(user.password)

        # 创建用户对象
        db_user = models.User(
            username=user.username,
            hashed_password=hashed_password,
            nickname=user.nickname
        )

        # 添加到数据库
        db.add(db_user)
        await db.commit()
        await db.refresh(db_user)
        return db_user
    except Exception as e:
        await db.rollback()
        logger.error(f"创建用户失败: {str(e)}")
        return None


async def authenticate_user(db: AsyncSession, username: str, password: str):
    """验证用户凭据 - 异步版本"""
    try:
        user = await get_user_by_username(db, username)
        if not user:
            return None
        if not security.verify_password(password, user.hashed_password):
            return None
        return user
    except Exception as e:
        logger.error(f"用户认证失败: {str(e)}")
        return None